package com.easonji.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.easonji.admin.dao.UserDAO;
import com.easonji.admin.model.Dept;
import com.easonji.admin.query.DeptQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.easonji.admin.dao.DeptDAO;
import com.easonji.admin.form.DeptForm;
import com.easonji.admin.manager.DeptManager;
import com.easonji.admin.mapper.DeptMapper;
import com.easonji.admin.service.DeptService;
import com.easonji.common.base.service.AbstractBaseService;
import com.easonji.common.constant.cache.CacheConsts;
import com.easonji.common.constant.cache.CacheKeyConsts;
import com.easonji.common.node.TreeNode;
import com.easonji.common.util.JsonUtils;
import com.easonji.common.util.StringUtils;
import com.easonji.core.annotion.CacheRemove;
import com.easonji.core.exception.BizException;

/**
 * @ClassName: DeptService
 * @Description: 部门服务实现类
 * @Author: LiuJun
 * @date: 2018/07/30 14:06:51
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
@Service
public class DeptServiceImpl extends AbstractBaseService<Dept> implements DeptService {

    @Resource
    private DeptMapper deptMapper;

    @Resource
    private DeptDAO deptDAO;

    @Resource
    private DeptManager deptManager;

    @Resource
    private UserDAO userDAO;

    @Override
    public Object queryDeptList(DeptQuery deptQuery) {
        // 查询条件
        Wrapper<Dept> wrapper = new EntityWrapper<>();
        String condition = deptQuery.getCondition();
        if (StringUtils.isNotEmpty(condition)) {
            wrapper.like("name", condition);
        }
        // 排序
        List<String> columns = new ArrayList<>();
        columns.add("parent_id");
        columns.add("num");
        wrapper.orderAsc(columns);
        List<Dept> depts = deptMapper.selectList(wrapper);
        return warp(depts);
    }

    @Override
    public Object queryDept(Integer deptId) {
        Dept dept = deptMapper.selectById(deptId);
        return warp(dept);
    }

    @Override
    @CacheRemove(value = CacheConsts.CONSTS, key = { CacheKeyConsts.DEPT })
    public Integer saveDept(DeptForm deptForm) {
        Dept dept = new Dept();
        BeanUtils.copyProperties(deptForm, dept);
        deptSetAllParentId(dept);
        return deptMapper.insert(dept);
    }

    @Override
    @CacheRemove(value = CacheConsts.CONSTS, key = { CacheKeyConsts.DEPT })
    public Integer updateDept(DeptForm deptForm) {
        Dept dept = new Dept();
        BeanUtils.copyProperties(deptForm, dept);
        deptSetAllParentId(dept);
        return deptMapper.updateById(dept);
    }

    @Override
    @Transactional(rollbackFor = BizException.class)
    @CacheRemove(value = CacheConsts.CONSTS, key = { CacheKeyConsts.DEPT })
    public void removeDept(Integer deptId) {
        // 查询部门
        Wrapper<Dept> wrapper = new EntityWrapper<>();
        wrapper.eq("id", deptId).or().like("all_parent_id", "[" + deptId + "]");
        // 删除该部门及子部门所有用户
        List<Dept> depts = deptMapper.selectList(wrapper);
        List<Integer> deptIds = new ArrayList<>();
        depts.forEach(dept -> {
            deptIds.add(dept.getId());
        });
        userDAO.updateUserDeptByDeptId(deptIds);
        // 删除部门
        deptMapper.delete(wrapper);
    }

    @Override
    public List<TreeNode> queryDeptTreeNode() {
        return deptDAO.selectDeptTreeNodes();
    }

    @Override
    protected JSONObject warp2Json(Dept dept) {
        JSONObject result = JsonUtils.parseObject(dept);
        Integer parentId = dept.getParentId();
        if (StringUtils.isEmpty(parentId) || parentId == 0) {
            result.put("parentName", "--");
        } else {
            result.put("parentName", deptManager.getDeptNameById(parentId));
        }
        return result;
    }

    /**
     * 根据父部门ID，设置全部父部门ID
     * 
     * @param dept
     *            部门信息
     */
    private void deptSetAllParentId(Dept dept) {
        int paretntId = dept.getParentId();
        if (StringUtils.isEmpty(paretntId) || paretntId == 0) {
            dept.setAllParentId("[0],");
        } else {
            Dept parentDept = deptMapper.selectById(paretntId);
            if (StringUtils.isNotEmpty(parentDept) && StringUtils.isNotEmpty(parentDept.getAllParentId())) {
                dept.setAllParentId(parentDept.getAllParentId() + "[" + paretntId + "],");
            }
        }
    }
}
